package com.faradel.pharmapp.managedbean;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.apache.commons.lang.StringUtils;
import org.faradel.pharmapp.entities.Medication;
import org.faradel.pharmapp.entities.MedicationInventory;
import org.faradel.pharmapp.entities.OrderMedication;
import org.faradel.pharmapp.entities.PharmaUser;
import org.springframework.context.ApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

import com.faradel.pharmapp.service.MedicationInventoryServiceInterface;
import com.faradel.pharmapp.service.OrderMedicationServiceInterface;

@ManagedBean
@ViewScoped
public class InventoryBean implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Resource
    private MedicationInventory medicationInventory;

    @Resource
    private Medication medication;

    @Resource
    OrderMedication orderMedication;

    private String medicationId;
    private PharmaUser currentUser;

    private List<MedicationInventory> inventoryList;

    private Map<String, String> searchMap = new HashMap<String, String>();

    private String action;

    // Popup flag
    private String message;

    private boolean showOrderAll;

    /**
     * Initialize
     */
    {
        ApplicationContext context = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        currentUser = (PharmaUser) extContext.getSessionMap().get("sessionUser");
        medication = (Medication) context.getBean("medication");
        medicationInventory = (MedicationInventory) context.getBean("medicationInventory");
        orderMedication = (OrderMedication) context.getBean("orderMedication");

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        inventoryList = new ArrayList<MedicationInventory>();

        action = params.get("action");
    }

    private MedicationInventoryServiceInterface getMedicationInventoryServiceInterface()
    {
        ApplicationContext context = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        return (MedicationInventoryServiceInterface) context.getBean("medicationInventoryServiceImpl");
    }

    private OrderMedicationServiceInterface getOrderMedicationServiceInterface()
    {
        ApplicationContext context = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        return (OrderMedicationServiceInterface) context.getBean("orderMedicationServiceImpl");
    }

    public void findInventoryById()
    {
        medicationInventory = getMedicationInventoryServiceInterface().getMedicationInventoryById(Integer.parseInt(medicationId));
        if (inventoryList.size() > 0)
            inventoryList.clear();
        inventoryList.add(medicationInventory);
    }

    public void findLowInventory()
    {
        if (StringUtils.isNotEmpty(medicationId))
            medicationId = null;

        if (inventoryList.size() > 0)
            inventoryList.clear();

        inventoryList = getMedicationInventoryServiceInterface().getLowInventory();

        if (inventoryList.size() > 1)
            showOrderAll = true;
    }

    public void findAllInventory()
    {
        if (StringUtils.isNotEmpty(medicationId))
            medicationId = null;

        if (inventoryList.size() > 0)
            inventoryList.clear();

        inventoryList = getMedicationInventoryServiceInterface().getAllMedicationInventory();
    }

    public String view()
    {
        action = "find";
        String s = "processinventoryorder";
        return s;
    }

    public void createInventoryOrder()
    {
        orderMedication.setMedication(medicationInventory.getMedication());
        orderMedication.setUnitPrice(medicationInventory.getCostPrice());
        orderMedication.setLastModified(TimeClass.getCurrentDate());
        orderMedication.setOrderOpenDate(TimeClass.getCurrentDate());
        orderMedication.setQuantity(calculateQuantity());
        orderMedication.setOrderStatus("Open");
        orderMedication.setTotalPrice(getTotalPrice());
        orderMedication.setSupplier(medicationInventory.getSupplier());
        orderMedication.setPharmaUser1(currentUser);
        orderMedication.setPharmaUser2(currentUser);

        getOrderMedicationServiceInterface().addOrderMedication(orderMedication);
        medicationInventory.setOrderStatus("Y");
        getMedicationInventoryServiceInterface().updateMedicationInventory(medicationInventory);

        message = "success";
    }

    public void orderAll()
    {
        for (MedicationInventory m : inventoryList)
        {
            medicationInventory = m;
            createInventoryOrder();
        }
        message = "success";
    }

    private int calculateQuantity()
    {
        int available = medicationInventory.getAvailableQuantity();
        int max = medicationInventory.getMaxQuantity();

        return max - available;
    }

    private BigDecimal getTotalPrice()
    {
        BigDecimal price = medicationInventory.getActualPriceSold();
        BigDecimal quantity = new BigDecimal(calculateQuantity());

        return price.multiply(quantity);
    }

    public MedicationInventory getMedicationInventory()
    {
        return medicationInventory;
    }

    public void setMedicationInventory(MedicationInventory medicationInventory)
    {
        this.medicationInventory = medicationInventory;
    }

    public Medication getMedication()
    {
        return medication;
    }

    public void setMedication(Medication medication)
    {
        this.medication = medication;
    }

    public String getMedicationId()
    {
        return medicationId;
    }

    public void setMedicationId(String medicationId)
    {
        this.medicationId = medicationId;
    }

    public List<MedicationInventory> getInventoryList()
    {
        return inventoryList;
    }

    public void setInventoryList(List<MedicationInventory> inventoryList)
    {
        this.inventoryList = inventoryList;
    }

    public Map<String, String> getSearchMap()
    {
        return searchMap;
    }

    public void setSearchMap(Map<String, String> searchMap)
    {
        this.searchMap = searchMap;
    }

    public String getAction()
    {
        return action;
    }

    public void setAction(String action)
    {
        this.action = action;
    }

    public boolean isShowOrderAll()
    {
        return showOrderAll;
    }

    public void setShowOrderAll(boolean showOrderAll)
    {
        this.showOrderAll = showOrderAll;
    }

    public OrderMedication getOrderMedication()
    {
        return orderMedication;
    }

    public void setOrderMedication(OrderMedication orderMedication)
    {
        this.orderMedication = orderMedication;
    }

    public PharmaUser getCurrentUser()
    {
        return currentUser;
    }

    public void setCurrentUser(PharmaUser currentUser)
    {
        this.currentUser = currentUser;
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }
}
